package
{
	import flash.display.DisplayObject;
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.LocationChangeEvent;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.geom.Rectangle;
	import flash.media.StageWebView;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.system.LoaderContext;
	import flash.utils.ByteArray;
	
	//545x383	1280*770
	[SWF(backgroundColor="#000000", width="545", height="383", frameRate="60", quality="LOW")]
	public class MinEntry extends Sprite
	{
		private var webView:StageWebView;
		private var flashvars:Object;
		private var entryUrl:String;
		
		private var oldid:String;  
		private var reg:RegExp = /<id>.*<\/id>/;  
		
		public function MinEntry()
		{
			windowedapplication_addedToStageHandler();
		}
		
		protected function windowedapplication_addedToStageHandler():void {
			var time:String = new Date().getTime()+"";
			var newid:String = "<id>qjMin"+time+"</id>";
			var f:File =new File(File.applicationDirectory.resolvePath("META-INF/AIR/application.xml").nativePath);
			if(f.exists) {
				var fs:FileStream = new FileStream();
				fs.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
				fs.open(f,FileMode.READ);
				var str:String = new String(fs.readUTFBytes(fs.bytesAvailable));
				oldid = str.match(reg).toString();
				str = str.replace(reg,newid);
				fs.open(f,FileMode.WRITE);
				fs.writeUTFBytes(str);
				fs.close();
			}
			
			initWebView();
			
			//有多个在运行的程序时只关闭一个运行程序就无法再打开新程序  
			//必须监听系统最后一个相同程序关闭时，才能初始化id  
			//解决办法：  
			//记录运行前id,若为初始ID则在关闭该程序时初始化id,否则不操作  
			if(oldid == "<id>qjMin</id>")
			{
				this.addEventListener(Event.CLOSE, returnId);
			}
		}
		
		private function errorHandler(event:IOErrorEvent):void { 
			trace("IOErrorEvent "+event.text);
		} 
		
		protected function returnId(e:Event):void  
		{
			var f:File =new File(File.applicationDirectory.resolvePath("META-INF/AIR/application.xml").nativePath);
			if(f.exists) {
				var fs:FileStream = new FileStream();
				fs.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
				fs.open(f,FileMode.READ);        
				var str:String = new String(fs.readUTFBytes(fs.bytesAvailable));  
				str = str.replace(reg,oldid);    
				fs.open(f,FileMode.WRITE);  
				fs.writeUTFBytes(str);   
				fs.close();
			}
		}
		
		private function initWebView():void {
			if(webView == null) {
				webView = new StageWebView();
			}
			webView.stage = this.stage;
			webView.viewPort = new Rectangle( 0, 0, stage.stageWidth, stage.stageHeight );
			webView.addEventListener(flash.events.LocationChangeEvent.LOCATION_CHANGE, handleLoad);
			webView.loadURL( "http://mu2.zhaouc.com/dlq/" );
		}
		
		private function handleLoad(event:flash.events.LocationChangeEvent):void {
			var d1:String = event.target.location;
			if(d1.indexOf("my.zhaouc.com/app/game2/index/gkey/ysdl/skey/") > -1) {
				webView.stop();
				webView.stage = null;
				webView.removeEventListener(flash.events.LocationChangeEvent.LOCATION_CHANGE, handleLoad);
				webView.dispose();
				webView = null;
				trace("d1="+d1);
				var loader:URLLoader  = new URLLoader ();
				loader.addEventListener(Event.COMPLETE, onCompleteHandler);
				loader.load(new URLRequest(d1+"?mytime="+new Date().getTime()));
			}
		}
		
		private function onCompleteHandler(event:Event):void {
			var d:Object = event.target;
			var d1:String = d.data;
//			trace("html="+d1);
			var d2:Array = d1.split("\n");
			var d3:Array = d2.filter(onCheck);
			flashvars = {};
			var s1:String;
			var s2:String;
			var d5:Array;
			var s3:String;
			var s4:String;
			var s5:String;
			var reg:RegExp = new RegExp('"',"g");
			var i:int=0;
			for(;i<d3.length;i++) {
				s1 = d3[i];
				s2 = s1.split(";")[0];
				d5 = s2.split("=");
				s3 = d5[1];//值
				s3 = s3.replace(reg, "");
				s3 = s3.replace(/\s+/g,"");
				s4 = d5[0];
				s5 = s4.split(".")[1];
				s5 = s5.replace(/\s+/g,"");
				flashvars[s5] = s3;
			}
			
			d3 = d2.filter(onCheck2);
			for(i=0;i<d3.length;i++) {
				s1 =d3[i];
				s2 = s1.split(",")[0];
				s2 = s2.replace(reg, "");
				s2 = s2.replace(/\s+/g,"");
				entryUrl = s2;
			}
			trace("entryUrl = "+entryUrl);
			if(entryUrl != null) {
				addLoadSwf();
			}
			else {
				//重新登录
				windowedapplication_addedToStageHandler();
			}
		}
		
		private function onCheck(value:*, index:int, arr:Array):Boolean {
			var f:Boolean = value.indexOf("flashvars.")>-1;
			return f;
		}
		//找出 http://cdn1.qiji.zhaouc.com/njdclient/Entry.swf?v=MJ3N8L
		private function onCheck2(value:*, index:int, arr:Array):Boolean {
			var f:Boolean = value.indexOf("Entry.swf")>-1;
			return f;
		}
		
		private function addLoadSwf():void {
			trace("addLoadSwf");
			var ur:URLRequest = new URLRequest();
			ur.url = entryUrl;
			ur.method = URLRequestMethod.GET;
			var entryLoader:URLLoader = new URLLoader();
			entryLoader.dataFormat = URLLoaderDataFormat.BINARY;
			entryLoader.addEventListener(Event.COMPLETE, onBytesLoader);
			entryLoader.load(ur);
		}
		
		private function onBytesLoader(event:Event):void {
			trace("onBytesLoader");
			var entryLoader:URLLoader = event.target as URLLoader;
			if(entryLoader != null) {
				var data:ByteArray = entryLoader.data;
				var con:LoaderContext = new LoaderContext();
				con.allowCodeImport = true;
				var loader:Loader = new Loader();
				loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onEntryCompleteHandler);
				loader.loadBytes(data, con);
				
				entryLoader.removeEventListener(Event.COMPLETE, onBytesLoader);
			}
		}
		
		private function onEntryCompleteHandler(event:Event):void {
			trace("onEntryCompleteHandler");
			var loaderinfo:LoaderInfo = event.target as LoaderInfo;
			if(loaderinfo != null) {
				var entryDisplay:DisplayObject = loaderinfo.content;
				stage.addChild(entryDisplay);
				(entryDisplay["onDesktopHandle"] as Function).call(null, flashvars);
				loaderinfo.removeEventListener(Event.COMPLETE, onEntryCompleteHandler);
				
				stage.nativeWindow.visible = true;
				stage.nativeWindow.maximize();
			}
		}
		
		
	}
}